package com.zkh360.service.message.auth;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import com.zkh360.service.message.util.MD5Util;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
	
	// 注入数据源
	@Autowired
	private DataSource dataSource;

	@Bean
	UserDetailsService customUserService() { // 注册UserDetailsService 的bean
		return new MyUserDetailsService();
	}

	@Bean(name = "authenticationManager")
	@Override
	public AuthenticationManager authenticationManagerBean() {
		AuthenticationManager authenticationManager = null;
		try {
			authenticationManager = super.authenticationManagerBean();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return authenticationManager;
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder() {

			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				return encodedPassword.equals(MD5Util.encode((String) rawPassword));
			}

			@Override
			public String encode(CharSequence rawPassword) {
				return MD5Util.encode((String) rawPassword);
			}
		}); // user Details Service验证;

	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
				// 关闭csrf保护功能（跨域访问）
				.csrf().disable().authorizeRequests().anyRequest().authenticated() // 任何请求,登录后可以访问
				.and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll() // 登录页面用户任意访问
				.and().logout().permitAll().invalidateHttpSession(true).and().rememberMe().tokenValiditySeconds(300)
				// 指定记住登录信息所使用的数据源
				.tokenRepository(tokenRepository());
		http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/css/**");
		web.ignoring().antMatchers("/js/**");
		web.ignoring().antMatchers("/img/**");
		web.ignoring().antMatchers("/webjars/**");
		web.ignoring().antMatchers("**/favicon.ico");
		web.ignoring().antMatchers("/ajax/**");
		web.ignoring().antMatchers("/fonts/**");
		web.ignoring().antMatchers("/less/**");
		web.ignoring().antMatchers("/pages/**");
		web.ignoring().antMatchers("/empty");
		web.ignoring().antMatchers("/index");
		web.ignoring().antMatchers("/error");
		web.ignoring().antMatchers("/gallery/**");
		web.ignoring().antMatchers("/assets/**");
		web.ignoring().antMatchers("/resume");
	}

	// spring security 内部都写死了，这里要把 这个DAO 注入
	@Bean
	public JdbcTokenRepositoryImpl tokenRepository() {
		JdbcTokenRepositoryImpl j = new JdbcTokenRepositoryImpl();
		j.setDataSource(dataSource);
		return j;
	}

}
